package com.itheima.web.manager;

import cn.hutool.captcha.LineCaptcha;
import cn.hutool.crypto.SecureUtil;
import com.itheima.domain.db.Admin;
import com.itheima.service.db.AdminService;
import com.itheima.util.ConstantUtil;
import com.itheima.util.JwtUtil;
import com.itheima.web.exception.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdminManager {

    @Reference
    private AdminService adminService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //生成验证码图片
    public LineCaptcha getVerification(String uuid) {
        //1. 调用工具类生成验证码
        LineCaptcha lineCaptcha = new LineCaptcha(300, 100, 4, 50);
        String code = lineCaptcha.getCode();
        System.out.println("验证码："+code);

        //2.将验证码存储到redis中(以uuid为键)
        stringRedisTemplate.opsForValue().set(ConstantUtil.ADMIN_CODE+uuid,code, Duration.ofMinutes(5));

        //3.返回验证码
        return lineCaptcha;
    }

    //登录，并返回token
    public String login(String username, String password, String verificationCode, String uuid) {
        //1.1从redis中查询验证码，失败返回
        String codeFromRedis = stringRedisTemplate.opsForValue().get(ConstantUtil.ADMIN_CODE + uuid);
        //1.2校验验证码是否正确
        if(!StringUtils.equals(verificationCode,codeFromRedis)){
            //不正确,返回错误
            throw new BusinessException("验证码错误!");
        }

        //2.调用adminService,查询用户名,失败返回
        Admin admin = adminService.findByUserName(username);
        if(admin == null){
            throw  new BusinessException("用户名错误!");
        }

        //3.验证密码,失败返回
        String passwordWithMd5 = SecureUtil.md5(password);
        //上面admin查询已经把密码带回来了
        if(!StringUtils.equals(passwordWithMd5,admin.getPassword())){
            throw  new BusinessException("密码错误!");
        }

        //模拟的未知性异常
        //int i = 1 / 0;

        //4. 说明登录成功
        //4.1 删除redis中的验证码
        stringRedisTemplate.delete(ConstantUtil.ADMIN_CODE+uuid);

        //4.2创建token并返回
        Map<String, Object> map = new HashMap<>();
        map.put("id",admin.getId());
        map.put("username",admin.getUsername());
        String token = JwtUtil.createToken(map);

        //token存入redis
        stringRedisTemplate.opsForValue().set(ConstantUtil.ADMIN_TOKEN+token,"登录用户token存储",Duration.ofHours(5));
        return token;
    }

    //查询用户信息
    public Admin findByUsername(String username) {
        Admin admin = adminService.findByUserName(username);
        return admin;
    }

    //用户退出
    public void logout(String token) {
        //本质上就是删除掉redis中当前用户的token
        stringRedisTemplate.delete(ConstantUtil.ADMIN_TOKEN + token);
    }
}
